use leptos::{prelude::*, task::spawn_local};
use shq_common::prelude::User;
use shq_web_controls::{use_message, MessageOptions, MessageVariant, ToastPosition, ToasterProvider};
use thaw_utils::ArcOneCallback;
use crate::{components::upload_file::UploadFile, shhr::{del_credit_report_file_by_fileid, del_credit_report_image_by_fileid, fetch_abnormal_record_by_frid, fetch_credit_report_abnormal, fetch_credit_report_image_by_frid, fetch_flow_run_step, save_credit_report_abnormal_record, save_credit_report_image_fileid_by_frid, update_credit_report_fileid_by_frid}, workflow::FlowRunList};
use std::collections::{BTreeMap, HashMap};
use serde_json::{ Map, Value };
use icondata as i;
use leptos_icons::*;
use shq_web_controls::MultiTreeSelect;


#[component]
pub fn CreditReport(menu_id: u32) -> impl IntoView {
    //成功或者错误提示信息
    let mess = use_message();
    let items = Resource::new(move || (), |_| fetch_credit_report_abnormal()); //获取异常列表
    let abnormal_ids = RwSignal::new(Vec::<String>::new());
    //左侧流程列表选中的数据
    let selected_emnm = RwSignal::new(String::new());
    let selected_emno = RwSignal::new(String::new());
    let selected_emid = RwSignal::new(u32::default());
    let selected_fileid = RwSignal::new(u32::default());
    let selected_ny = RwSignal::new(u32::default());
    let selected_frid = RwSignal::new(u32::default());
    let showImportModel = RwSignal::new(false);
    let showImportImageModel = RwSignal::new(false);
    let open_pdf = RwSignal::new(false);
    let open_image = RwSignal::new(true);
    let images_map: RwSignal<HashMap<u64, u64>> = RwSignal::new(HashMap::new());

    let curr_user = use_context::<RwSignal<Option<User>>>().unwrap();
    let emid = curr_user.with(|u| u.as_ref().map(|u| u.id)).unwrap();
    //获取当前所在流程节点
    let stepids = Resource::new(
        move || selected_frid.get(),
        move |frid| async move{ 
            let stepid = fetch_flow_run_step(frid,emid).await;
            stepid
         }
    );

    //获取用户已勾选记录
    let abnormal_items = Resource::new(
        move || selected_frid.get(),
        move |frid| async move{ 
            let abnormals = fetch_abnormal_record_by_frid(frid).await;
            abnormals
         }
    );

    let sel_abnormal_ids = Memo::new(move |_| {
        let sel_abnormal_ids: Vec<String> = abnormal_items.get()
            .iter()
            .flat_map(|abnormal_id_result| match abnormal_id_result {
                Ok(abnormal_ids) => abnormal_ids.iter()
                    .map(|id| {
                        // 处理转义引号，移除多余的引号
                        let s = format!("{:?}", id);
                        s.trim_matches('"').to_string()
                    })
                    .collect::<Vec<String>>(),
                Err(_) => vec![],
            })
            .collect();
        sel_abnormal_ids
    });
    //获取图片列表
    let images = Resource::new(
        move || selected_frid.get(),
        move |frid| async move{ 
            let image = fetch_credit_report_image_by_frid(frid).await;
            image
         }
    );
    create_effect(move |_| {
        if let Some(Ok(value)) = images.get() {
            images_map.set(value);
        }
    });

    //导入后的回调
    let on_upload = ArcOneCallback::new(
        move |fileids: Vec<u64>| {
            if fileids.len() > 0 {
                selected_fileid.set(fileids[0] as u32);
                if selected_frid.get() != 0 || selected_emid.get() != 0 {
                    let emid = selected_emid.get();
                    let emnm = selected_emnm.get();
                    let emno = selected_emno.get();
                    let ny = selected_ny.get();
                    let frid = selected_frid.get();
                    spawn_local(async move{
                        match update_credit_report_fileid_by_frid(ny,frid,emid,emno,emnm,fileids).await {
                            Ok(_) => {
                                mess.create("导入成功", MessageVariant::Success, MessageOptions::default());
                                showImportModel.set(false);
                            }
                            Err(e) => {
                                mess.create(
                                    format!("导入失败：{}", e),
                                    MessageVariant::Error,
                                    MessageOptions::default()
                                );
                            }
                        };
                    });
                } else {
                    // 处理home_visit_empl_id为None的情况
                    mess.create("没有有效的流程ID", MessageVariant::Error, MessageOptions::default());
                }
            }
        }
    );
    let image_on_upload = ArcOneCallback::new(
        move |fileId: Vec<u64>| {
            let emid = selected_emid.get();
            let emnm = selected_emnm.get();
            let emno = selected_emno.get();
            let ny = selected_ny.get();
            let frid = selected_frid.get();
            if fileId.len() > 0 {
                images_map.update(|map| {
                    // 找到当前map中最大的key，如map为空则使用0
                    let max_key = map.keys().max().copied().unwrap_or(0);
                    // 新key为最大key+1
                    let new_key = max_key + 1;
                    // 插入新键值对
                    map.insert(new_key, fileId[0]);
                });
                if selected_frid.get() != 0 || selected_emid.get() != 0 {
                    spawn_local(async move{
                        match save_credit_report_image_fileid_by_frid(ny, frid, emid, emno, emnm, fileId).await {
                            Ok(_) => {
                                mess.create("导入成功", MessageVariant::Success, MessageOptions::default());
                                // showImportImageModel.set(false);
                            }
                            Err(e) => {
                                mess.create(
                                    format!("导入失败：{}", e),
                                    MessageVariant::Error,
                                    MessageOptions::default()
                                );
                            }
                        };
                    });
                } else {
                    // 处理home_visit_empl_id为None的情况
                    mess.create("没有有效的流程ID", MessageVariant::Error, MessageOptions::default());
                }
            }
        }
    );
    //导入模块的展示
    let specialist_management = move || {
        let on_upload=on_upload.clone();
        if showImportModel.get() && (stepids.get().and_then(|r| r.ok()) == Some(1)||stepids.get().and_then(|r| r.ok()) == Some(3)) {
            Some(view! {
                <dialog id="data_import_modal" class="modal modal-open  z-50">
                    <div class="modal-box overflow-hidden max-w-md max-h-[80vh]">
                        <button class="absolute right-2 top-2" on:click=move|_|{
                            showImportModel.set(false);
                        }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                        </button>
                        <h3 class="text-lg font-bold">导入征信文件</h3>
                        <div class="p-2">
                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                <UploadFile accept=".pdf" on_upload/>
                            </Suspense>
                        </div>
                    </div>
                </dialog>
            })
        }else {
            None
        }
    };
    let specialist_management2 = move || {
        let image_on_upload=image_on_upload.clone();
        if showImportImageModel.get() && (stepids.get().and_then(|r| r.ok()) == Some(1)||stepids.get().and_then(|r| r.ok()) == Some(3)) {
            Some(view! {
                <dialog id="data_import_modal" class="modal modal-open  z-50">
                    <div class="modal-box overflow-hidden max-w-md max-h-[80vh]">
                        <button class="absolute right-2 top-2" on:click=move|_|{
                            showImportImageModel.set(false);
                        }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                        </button>
                        <h3 class="text-lg font-bold">导入消费凭证</h3>
                        <div class="p-2">
                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                <UploadFile accept=".png" on_upload=image_on_upload/>
                            </Suspense>
                        </div>
                    </div>
                </dialog>
            })
        }else {
            None
        }
    }; 

    //保存异常记录勾选情况
    let save_abnormal_record = Action::new(move|_|{
        let emid = selected_emid.get();
        let emnm = selected_emnm.get();
        let emno = selected_emno.get();
        let ny = selected_ny.get();
        let frid = selected_frid.get();
        let mut abnormal_ids = abnormal_ids.get();
        if abnormal_ids.is_empty() {
            // abnormal_ids = vec![0];
            abnormal_ids = vec![];
        }
        let abnormal_ids_result: Result<Vec<u64>, _> = abnormal_ids.iter()
                .map(|id| id.parse::<u64>())
                .collect();
        let abnormal_ids = match abnormal_ids_result {
                Ok(ids) => ids,
                Err(e) => {
                    mess.create(
                        format!("保存失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                    Vec::new()
                }
        };
        async move{
            match save_credit_report_abnormal_record(ny,frid,emid,emno,emnm,abnormal_ids).await {
                Ok(_) => {
                    mess.create("保存成功", MessageVariant::Success, MessageOptions::default());
                }
                Err(e) => {
                    mess.create(
                        format!("保存失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                }
            }
        }
    });

    let remove_by_value = move |target_value: u64| {
        images_map.update(|map| {
            map.retain(|_, &mut v| v != target_value);
        });
    };
    //删除征信图片
    let del_credit_report_image = Action::new(move|&(fileid):&(u64)|{
        async move{
            match del_credit_report_image_by_fileid(fileid).await {
                Ok(_) => {
                    // 根据 value 删除所有匹配的键值对
                    remove_by_value(fileid);
                    mess.create("删除成功", MessageVariant::Success, MessageOptions::default());
                }
                Err(e) => {
                    mess.create(
                        format!("删除失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                }
            }
        }
    });
    //删除征信文件
    let del_credit_report_file = Action::new(move|&(fileid,frid):&(u32,u32)|{
        async move{
            match del_credit_report_file_by_fileid(fileid,frid).await {
                Ok(_) => {
                    selected_fileid.set(0);
                    mess.create("删除成功", MessageVariant::Success, MessageOptions::default());
                }
                Err(e) => {
                    mess.create(
                        format!("删除失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                }
            }
        }
    });

    // Effect::new(move |_| {
    //     if let Some(Ok(saved_abnormals)) = abnormal_items.get() {
    //         abnormal_ids.set(saved_abnormals.clone());
    //     }
    // });
    let on_change = move |values: Vec<String>| {
        abnormal_ids.set(values);
    };
    let abnormals = move||{
        view! {
            {move || match items.get() {
                Some(Ok(abnormals)) => {
                    // let sorted_map: BTreeMap<_, _> = abnormal_map.into_iter().collect();
                    let tree_items = StoredValue::new(abnormals.into());
                    view! {
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 h-full flex flex-col">
                            <div class="p-4 border-b border-gray-200 flex items-center gap-2">
                                <Icon 
                                    icon=i::AiFilePdfOutlined 
                                    width="20" 
                                    height="20"
                                />
                                <span class="text-lg font-medium">征信异常类型</span>
                            </div>
                            <div class="p-4 flex-1 flex flex-col">
                                <div class="flex items-center justify-start mb-4 gap-2 flex-wrap">
                                    <button class="btn btn-primary transition-all"
                                        on:click=move|_|{
                                            if selected_frid.get() == 0 || selected_emid.get() == 0 {
                                                mess.create("请先选择员工！", MessageVariant::Warning, MessageOptions::default());
                                                return;
                                            }
                                            save_abnormal_record.dispatch(());
                                        }
                                    >
                                        {"保存"}
                                    </button>
                                    <button class="btn btn-primary transition-all"
                                        on:click= move |_| {
                                            if selected_frid.get() == 0 || selected_emid.get() == 0 {
                                                mess.create(
                                                    "请选择要导入的用户！", 
                                                    MessageVariant::Success, 
                                                    MessageOptions::default()
                                                );
                                                return;
                                            }
                                            showImportModel.set(true);
                                        }
                                    >
                                        {"上传征信报告"}
                                    </button>
                                    <button class="btn btn-primary transition-all"
                                        on:click= move |_| {
                                            if selected_frid.get() == 0 || selected_emid.get() == 0 {
                                                mess.create(
                                                    "请选择要导入的用户！", 
                                                    MessageVariant::Success, 
                                                    MessageOptions::default()
                                                );
                                                return;
                                            }
                                            showImportImageModel.set(true);
                                        }
                                    >
                                        {"上传消费凭证"}
                                    </button>
                                </div>
                                <div class="flex-1 overflow-y-auto min-h-1">
                                    <MultiTreeSelect
                                        tree_items
                                        show_confirm_cancel_btn=false
                                        on_change
                                        values = sel_abnormal_ids.get()
                                    />
                                </div>
                                // <div class="space-y-2 overflow-y-auto flex-1 p-1">
                                //     {sorted_map.iter().map(|(id, name)| {
                                //         let id_val = *id;
                                //         let id_str = id.to_string();
                                //         let name_str = name.clone();

                                //         let is_checked = Memo::new(move |_| {
                                //             abnormal_ids.get().contains(&id_val)
                                //         });
                                //         let abnormal_ids = abnormal_ids.clone();
                                //         view! {
                                //             <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors">
                                //                 <input
                                //                     type="checkbox"
                                //                     value=id_str
                                //                     checked=is_checked
                                //                     class="checkbox checkbox-sm border-gray-400 [--chkbg:theme(colors.indigo.600)] [--chkfg:white] checked:border-indigo-600"
                                //                     on:change={move |ev| {
                                //                         let checked = event_target_checked(&ev);
                                //                         abnormal_ids.update(move |ids| {
                                //                             if checked {
                                //                                 // 仅在不存在时添加，避免重复
                                //                                 if !ids.contains(&id_val) {
                                //                                     ids.push(id_val);
                                //                                     // 保持数组有序
                                //                                     ids.sort_unstable();
                                //                                 }
                                //                             } else {
                                //                                 // 移除指定ID
                                //                                 ids.retain(|&x| x != id_val);
                                //                             }
                                //                         });
                                //                     }}
                                //                 />
                                //                 <div class="flex-1">
                                //                     <span class="font-medium">{name_str}</span>
                                //                 </div>
                                //             </label>
                                //         }
                                //     }).collect::<Vec<_>>()}
                                // </div>
                            </div>
                        </div>
                    }.into_any()
                }
                Some(Err(e)) => {
                    view! {
                        <div class="p-4 text-red-500">
                            {e.to_string()}
                        </div>
                    }.into_any()
                }
                None => {
                    view! {
                        <div class="flex-1 flex items-center justify-center">
                            "正在加载菜单数据..."
                        </div>
                    }.into_any()
                }
            }}
        }
    };
    
    let image = move || {
        view! {
            {move || {
                let image_map = images_map.get();
                // 创建一个新的BTreeMap来排序，避免所有权问题
                let sorted_map: BTreeMap<_, _> = image_map.into_iter().collect();
                view! {
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 h-full flex flex-col">
                        // <div class="p-4 border-b border-gray-200 flex items-center gap-2">
                        //     <Icon 
                        //         icon=i::AiFilePdfOutlined 
                        //         width="20" 
                        //         height="20"
                        //     />
                        //     <span class="text-lg font-medium">消费凭证</span>
                        // </div>
                        <div class="p-4 flex-1 flex flex-col">
                            {if sorted_map.is_empty() {
                                view! {
                                    <div class="flex-1 flex flex-col items-center justify-center text-gray-500 p-8">
                                        <Icon icon=i::AiPictureOutlined width="48" height="48"/>
                                        <p>暂无图片数据</p>
                                    </div>
                                }.into_any()
                            } else {
                                // 创建信号来跟踪当前显示的图片索引
                                let current_index = RwSignal::new(0usize);
                                view! {
                                    <>
                                        <div class="carousel-container mb-4 flex-1 flex items-center justify-center">
                                            <div class="carousel w-full bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden" 
                                                style="max-width: 100%; height: 600px;">
                                                {sorted_map.iter().enumerate().map(|(index, (id, name))| {
                                                    let item_id = format!("item{}", index + 1);
                                                    let name_clone = name.clone();
                                                    let is_active = move || current_index.get() == index;
                                                    
                                                    view! {
                                                        <div id={item_id.clone()} class=move || format!("carousel-item w-full h-full relative {}", if is_active() { "" } else { "hidden" })>
                                                            <button class="absolute top-2 right-2 btn btn-error btn-outline btn-sm z-10 bg-white/80 hover:bg-white transition-all"
                                                                on:click=move |_| {
                                                                    if stepids.get().and_then(|r| r.ok()) == Some(1)||stepids.get().and_then(|r| r.ok()) == Some(3){
                                                                        // 在这里添加删除图片的逻辑
                                                                        del_credit_report_image.dispatch(name_clone);
                                                                    }
                                                                }
                                                            >
                                                                <Icon icon=i::AiDeleteOutlined width="16" height="16"/>
                                                                {"删除"}
                                                            </button>
                                                            <img
                                                                src={format!("/binary_file/{}", name_clone)}
                                                                alt="消费凭证"
                                                                class="object-contain mx-auto"
                                                                style="width: 100%; height: 100%;"
                                                                loading="lazy"
                                                                on:error=move |_| {
                                                                    leptos::logging::error!("Failed to load image: {}", name_clone);
                                                                }
                                                            />
                                                        </div>
                                                    }
                                                }).collect::<Vec<_>>()}
                                            </div>
                                        </div>
                                        <div class="flex justify-center gap-2 py-2 mt-auto">
                                            {sorted_map.iter().enumerate().map(|(index, (id, _))| {
                                                view! {
                                                    <button
                                                        class=move || format!("btn btn-xs {}", if current_index.get() == index { "btn-primary" } else { "btn-outline" })
                                                        on:click=move |_| current_index.set(index)
                                                    >
                                                        {(index + 1).to_string()}
                                                    </button>
                                                }
                                            }).collect::<Vec<_>>()}
                                        </div>
                                    </>
                                }.into_any()
                            }}
                        </div>
                    </div>
                }.into_any()
            }}
        }
    };


    let credit_report_file = move || {
        view! {
            <div class="flex flex-1 flex-col gap-4 p-4 overflow-hidden bg-gray-50">
                {/* 上方区域：异常提示和轮播图 - 使用Collapse组件 */}
                <div class="space-y-4">
                    <div class="h-full min-h-[300px]">
                        {abnormals}
                    </div>
                    // <div class="collapse collapse-arrow bg-white rounded-lg shadow-sm border border-gray-200">
                    //     <input type="checkbox" class="peer" />
                    //     <div class="collapse-title p-4 flex items-center gap-2 text-lg font-medium">
                    //         <Icon icon=i::AiFilePdfOutlined width="20" height="20"/>
                    //         <span>征信异常类型</span>
                    //     </div>
                    //     <div class="collapse-content">
                    //         <div class="p-4 flex-1 flex flex-col">
                    //             {abnormals}
                    //         </div>
                    //     </div>
                    // </div>

                    {/* 消费凭证 Collapse */}
                    <div class="collapse collapse-arrow bg-white rounded-lg shadow-sm border border-gray-200">
                        <input 
                            type="checkbox" 
                            checked=move || open_image.get()
                            class="peer" 
                            on:change=move |e| {
                                let checked = event_target_checked(&e);
                                open_image.set(checked);
                                if checked {
                                    open_image.set(false);
                                }
                            }
                        />
                        <div class="collapse-title p-4 flex items-center gap-2 text-lg font-medium">
                            <Icon icon=i::AiFileImageOutlined width="20" height="20"/>
                            <span>消费凭证</span>
                        </div>
                        <div class="collapse-content">
                            <div class="p-4 flex-1 flex flex-col">
                                {image}
                            </div>
                        </div>
                    </div>
                </div>
                
                {/* 下方区域：征信明细表 */}
                <div class="collapse collapse-arrow bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                    <input 
                        type="checkbox"
                        checked=move || open_pdf.get()
                        class="peer"
                        on:change=move |e| {
                            let checked = event_target_checked(&e);
                            open_pdf.set(checked);
                            if checked {
                                open_pdf.set(false);
                            }
                        }
                    />
                    <div class="collapse-title p-4 flex items-center gap-2 text-lg font-medium">
                        <Icon icon=i::AiFilePdfOutlined width="20" height="20"/>
                        <span>征信明细表</span>
                    </div>
                    <div class="collapse-content">
                        <div class="flex-1 bg-gray-50 flex items-center justify-center min-h-[400px]">
                            <button class="absolute top-2 right-2 btn btn-error btn-outline btn-sm z-10 bg-white/80 hover:bg-white transition-all"
                                on:click=move |_| {
                                    if stepids.get().and_then(|r| r.ok()) == Some(1)||stepids.get().and_then(|r| r.ok()) == Some(3){
                                        // 在这里添加删除PDF的逻辑
                                        del_credit_report_file.dispatch((selected_fileid.get(),selected_frid.get()));
                                    }
                                }
                            >
                                <Icon icon=i::AiDeleteOutlined width="16" height="16"/>
                                {"删除"}
                            </button>
                            <object 
                                data={format!("/binary_file/{}", selected_fileid.get())} 
                                type="application/pdf" 
                                class="w-full h-full min-h-[800px]"
                            >
                                <div class="flex flex-col items-center justify-center h-full text-gray-500 text-lg p-8">
                                    <Icon icon=i::AiFilePdfOutlined width="48" height="48"/>
                                    <p>无法加载PDF文档</p>
                                    {if selected_fileid.get() == 0 {
                                        view! { <p class="text-sm mt-2">请先选择员工并上传征信报告</p> }.into_any()
                                    } else {
                                        view! { <p class="text-sm mt-2">文件ID: {selected_fileid.get()}</p> }.into_any()
                                    }}
                                </div>
                            </object>
                        </div>
                    </div>
                </div>
            </div>
        }
    };


    let on_row_select_change_run = ArcOneCallback::new(
        move |selected_rows: Option<Map<String, Value>>| {
            if let Some(rows) = selected_rows {
                if let Some(Value::Number(value)) = rows.get("ny") {
                    if let Some(ny) = value.as_u64().map(|x| x as u32) {
                        selected_ny.set(ny);
                    }
                }
                if let Some(Value::Number(value)) = rows.get("frid") {
                    if let Some(frid) = value.as_u64().map(|x| x as u32) {
                        selected_frid.set(frid);
                    }
                }
                if let Some(Value::Number(emid)) = rows.get("emid") {
                    if let Some(value) = emid.as_u64().map(|x| x as u32) {
                        selected_emid.set(value);
                    }
                }
                if let Some(Value::Number(fileid)) = rows.get("file_id") {
                    if let Some(value) = fileid.as_u64().map(|x| x as u32) {
                        selected_fileid.set(value);
                    }
                }
                if let Some(Value::String(emnm_value)) = rows.get("emnm") {
                    selected_emnm.set(emnm_value.clone());
                }
                if let Some(Value::String(emno_value)) = rows.get("emno") {
                    selected_emno.set(emno_value.clone());
                }
            }
        }
    );

    view!{
         <div class="flex flex-1 w-full h-full overflow-hidden bg-white">
            <div class="flex flex-col w-1/3 bg-gray-100 border-r border-gray-300">
                <div class="flex-1 p-4">
                    <FlowRunList menu_id wfid=1u32 on_row_select_change=on_row_select_change_run/>
                </div>
            </div>
            <div class="flex flex-col flex-1 bg-gray-100 border-r border-gray-100 overflow-y-auto ">
                <div class="flex-1 p-4">
                    <Suspense fallback=|| view! { <progress class="progress progress-primary w-56"></progress> }>
                        {credit_report_file}
                    </Suspense>
                </div>
            </div>
            // 提示信息容器
            <ToasterProvider position=ToastPosition::TopStart>
                {specialist_management}
                {specialist_management2}
            </ToasterProvider>
        </div>
    }
}
